'use strict';

function OpenCode() {
    //var xml = Blockly.Xml.textToDom(xml_text);
    //Blockly.Xml.domToWorkspace(xml, workspace);
    NewBlockCode();
    ///var xml =BlocksToXml();
    //var xml = BlocksToPython();
    //alert(xml);
    /*var url = 'test.xml';
    if (!url) {
      url = window.prompt('Enter URL of test file.');
      if (!url) {
        return;
      }
    }
    var xmlText = fetchFile(url);
    //alert(xmlText);
    //var xmlDoc = Blockly.Xml.textToDom(xmlText);
    //Blockly.Xml.domToWorkspace(xmlDoc, workspace);   
    if (xmlText != null) {
      fromXml(xmlText);
    }
    BlocklyStorage.restoreBlocks();*/
}

function XmlToCode() {
    var input = document.getElementById('importExport');
    var xml = Blockly.Xml.textToDom(input.value);
    Blockly.Xml.domToWorkspace(xml, workspace);
    taChange();
}

function SaveCode() {


    /*  var xml = Blockly.Xml.workspaceToDom(workspace);
      var xml_text = Blockly.Xml.domToText(xml);
      alert(xml_text);*/
    var output = document.getElementById('importExport');
    var xml = Blockly.Xml.workspaceToDom(workspace);

    // if (xml.childElementCount == 1) {
    //     return null;
    // }
    xml = Blockly.Xml.domToPrettyText(xml);
    var xml2 = xml.replace('#ff0000', '#cccccc');
    output.value = xml2;
    output.focus();
    output.select();
    taChange();
}

function BuildCode() {
    /*Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
    var code = Blockly.Python.workspaceToCode(workspace);
    alert(code);*/
    var output = document.getElementById('importExport');
    output.value = Blockly.Python.workspaceToCode(workspace);
    //output.focus();
    //output.select();
    // Blockly.Events.element = 'click';

    taChange();
}

function undo() {
    workspace.undo(false)
}

function redo() {
    workspace.undo(true);
}

function fetchFile(xmlUrl) {
    try {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('GET', xmlUrl, false);
        xmlHttp.setRequestHeader('Content-Type', 'text/xml');
        xmlHttp.send('');
    } catch (e) {
        // Attempt to diagnose the problem.
        var msg = 'Error: Unable to load XML data.\n';
        if (window.location.protocol == 'file:') {
            msg += 'This may be due to a security restriction preventing\n' +
                'access when using the file:// protocol.\n' +
                'Use an http webserver, or a less paranoid browser.\n';
        }
        alert(msg + '\n' + e);
        return null;
    }
    return xmlHttp.responseText;
}

function saveFile(xmlUrl) {
    try {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('PUT', 'test.xml', false);
        xmlHttp.setRequestHeader('Content-Type', 'text/xml');
        xmlHttp.send(xmlUrl);
    } catch (e) {
        // Attempt to diagnose the problem.
        var msg = 'Error: Unable to load XML data.\n';
        if (window.location.protocol == 'file:') {
            msg += 'This may be due to a security restriction preventing\n' +
                'access when using the file:// protocol.\n' +
                'Use an http webserver, or a less paranoid browser.\n';
        }
        alert(msg + '\n' + e);
        return null;
    }
}

function fromXml(xmlText) {
    //var output = document.getElementById('importExport');
    //output.value = xmlText;
    //output.scrollTop = 0;
    //output.scrollLeft = 0;
    workspace.clear();
    try {
        var xmlDocBlock = Blockly.Xml.textToDom(xmlText);
    } catch (e) {
        alert('Error parsing XML:\n' + e);
        return;
    }
    Blockly.Xml.domToWorkspace(xmlDocBlock, workspace);
}
function fromXml2(xmlText) {
    //var output = document.getElementById('importExport');
    //output.value = xmlText;
    //output.scrollTop = 0;
    //output.scrollLeft = 0;
    //workspace.clear();
    try {
        var xmlDocBlock = Blockly.Xml.textToDom(xmlText);
    } catch (e) {
        alert('Error parsing XML:\n' + e);
        return;
    }
    Blockly.Xml.appendDomToWorkspace(xmlDocBlock, workspace);
}

//Text charge
function taChange() {
    var textarea = document.getElementById('importExport');
    if (sessionStorage) {
        sessionStorage.setItem('textarea', textarea.value);
    }
    var valid = true;
    try {
        Blockly.Xml.textToDom(textarea.value);
    } catch (e) {
        valid = false;
    }
    //document.getElementById('import').disabled = !valid;
}

//获取当前区域图形控件
function BlocksToXml() {
    var temp = Blockly.Xml.workspaceToDom(workspace, true);
    // if (temp.childElementCount == 1) {
    //     return null;
    // }
    var xml = Blockly.Xml.domToPrettyText(temp);
    return xml;
}

//获取当前图形化编译结果
function BlocksToPython() {
    var output = document.getElementById('importExport');
    var codePython = Blockly.Python.workspaceToCode(workspace);
    return codePython;
}

//新建空白的编程区域：NewBlockCode
function NewBlockCode() {
    var xml = '<xml xmlns="http://www.w3.org/1999/xhtml">'
    xml += ' <variables></variables>';
    xml += '<block type="Goertek_Start" id="rS*OrEH@}i9,3U2TLIqz" x="100" y="20"></block>';
    xml += '</xml>';
    workspace.clear();
    try {
        var xmlDoc1 = Blockly.Xml.textToDom(xml);
    } catch (e) {
        alert('Error parsing XML:\n' + e);
        return;
    }
    Blockly.Xml.domToWorkspace(xmlDoc1, workspace);
}

//打开保存好的block文件
function OpenBlocks(strBlocks) {
    var xmlText = strBlocks;
    if (xmlText != null) {
        fromXml(xmlText);
    }
}
function OpenBlocks2(strBlocks) {
    var xmlText = strBlocks;
    if (xmlText != null) {
        fromXml2(xmlText);
    }
}
// //获取当前区域图形控件
// var starttime = '00:00';
// //获取ada传给我的时间
// function getTime(gettime) {
//     // workspace.addChangeListener(myUpdateFunction);
//     starttime = gettime;
// }

// function myUpdateFunction(event) {
//     //BuildCode();
//     // var xml = changetime(starttime);
// }
var lengthnext1 = 0;
var lengthnext2 = 0;
var statementLen1 = 0;
var statementLen2 = 0;
//时间快显示时间
// function changetime(starttime) {

//     var boolnext = false;
//     var temp = Blockly.Xml.workspaceToDom(workspace);
//     var xml = Blockly.Xml.domToPrettyText(temp);
//     var parser = new DOMParser();
//     var xmlDoc = parser.parseFromString(xml, "text/xml");
//     var countrys = xmlDoc.getElementsByTagName('field');
//     //判断正常插入next
//     var countrys1 = xmlDoc.getElementsByTagName('next');
//     lengthnext1 = countrys1.length;
//     var comparealenth = lengthnext1 - 1;
//     if (comparealenth == lengthnext2) {
//         boolnext = true;
//     }
//     lengthnext2 = lengthnext1;
//     //判断控件在时间中插入卡顿问题
//     var arr = [];
//     var statement = xmlDoc.getElementsByTagName('statement');
//     statementLen1 = statement.length;
//     var comparealenth2 = statementLen1 - 1;
//     if (comparealenth2 == statementLen2) {
//         boolnext = true;
//     }
//     statementLen2 = statementLen1;

//     //判断新来的块00:00

//     if (boolnext == true) {
//         boolnext = false;
//         if (countrys.length >= 1) {
//             arr = [];
//             for (var i = 0; i < countrys.length; i++) {
//                 arr.push(countrys[i].textContent);
//             };
//             for (var i = 0; i < countrys.length; i++) {
//                 if (arr[i] == "00:00") {
//                     var colornum = xmlDoc.getElementsByTagName("field")[i].childNodes[0];
//                     colornum.nodeValue = starttime;
//                     xml = new XMLSerializer().serializeToString(xmlDoc);
//                     workspace.clear();
//                     try {
//                         var xmlDoc1 = Blockly.Xml.textToDom(xml);
//                     } catch (e) {
//                         alert('Error parsing XML:\n' + e);
//                         return;
//                     }
//                     Blockly.Xml.domToWorkspace(xmlDoc1, workspace);
//                     break;

//                 }
//             };
//         }

//     }
//     boolnext = false;
//     return xml;
// }
//自己调试用
function changecolor2() {
    var aaa = '01:01';
    var bb = 0;
    //getTime(aaa);
    setcolor(aaa, bb);
}
//自己调试用
function changecolor() {
    var aaa = '01:01';
    getTime(aaa);
    // setcolor(aaa);
}
//设置时间快颜色
function setcolor(colortime) {
    var blocks = workspace.getAllBlocks();

    for (var i = 0; i < blocks.length; i++) {
        var block = blocks[i];
        if (block.type == "block_inittime") {
            if (colortime == block.getFieldValue("time")) {
                block.setFieldValue("#33ff33", "color");
            } else {
                block.setFieldValue("#cccccc", "color");
            }
        }
    }

    // var temp = Blockly.Xml.workspaceToDom(workspace);
    // if (temp.childElementCount == 1) {
    //     return null;
    // }
    // var xml = Blockly.Xml.domToPrettyText(temp);

    // var parser = new DOMParser();
    // var xmlDoc = parser.parseFromString(xml, "text/xml");


    // //提取数据  
    // var countrys = xmlDoc.getElementsByTagName('field');


    // var arr = [];
    // var b = 0;
    // var boolblock = 0;
    // var colorboolblock = 0;
    // for (var i = 0; i < countrys.length; i++) {
    //     arr.push(countrys[i].textContent);
    // }

    // for (var i = 0; i < countrys.length; i++) {
    //     if (arr[i] == "#33ff33") {
    //         var colornum = xmlDoc.getElementsByTagName("field")[i].childNodes[0];
    //         colornum.nodeValue = "#cccccc";
    //     }
    //     if (arr[i] == "#ffff00") {
    //         var colornum = xmlDoc.getElementsByTagName("field")[i].childNodes[0];
    //         colornum.nodeValue = "#cccccc";
    //     }
    // }

    // for (var i = 0; i < countrys.length; i++) {
    //     if (arr[i] == colortime) {
    //         //第一个变绿色
    //         b = i + 1;
    //         var d = xmlDoc.getElementsByTagName("field")[b].childNodes[0];
    //         d.nodeValue = "#33ff33";
    //         boolblock = 1;
    //     }
    // }

    /*自动在左上角生成快，不用就注释了
    if(boolblock==0)
    {
      var newel=xmlDoc.createElement("block");
      var x=xmlDoc.getElementsByTagName("xml")[0];
      x.appendChild(newel);  
      var newatt=xmlDoc.createAttribute("type");
      newatt.nodeValue="block_inittime";
      x=xmlDoc.getElementsByTagName("block");    
      x[x.length-1].setAttributeNode(newatt);
      var id=xmlDoc.createAttribute("id");
      id.nodeValue="111";
      x=xmlDoc.getElementsByTagName("block");    
      x[x.length-1].setAttributeNode(id);
      var blockX=xmlDoc.createAttribute("x");
      blockX.nodeValue="0";
      x=xmlDoc.getElementsByTagName("block");    
      x[x.length-1].setAttributeNode(blockX);
      var blockY=xmlDoc.createAttribute("y");
      blockY.nodeValue="0";
      x=xmlDoc.getElementsByTagName("block");    
      x[x.length-1].setAttributeNode(blockY);

      var field=xmlDoc.createElement("field");
      var timetext=xmlDoc.createTextNode(colortime);
      field.appendChild(timetext);
      var blockLenth = xmlDoc.getElementsByTagName('block'); 
      var fieldindex=xmlDoc.getElementsByTagName("block")[blockLenth.length-1];
      fieldindex.appendChild(field);

      var sec=xmlDoc.createAttribute("name");
      sec.nodeValue="sec";
      x=xmlDoc.getElementsByTagName("field");    
      x[x.length-1].setAttributeNode(sec);

      var field2=xmlDoc.createElement("field");
      var colortext=xmlDoc.createTextNode("#33ff33");
      field2.appendChild(colortext);
      var blockLenth2 = xmlDoc.getElementsByTagName('block'); 
      var fieldindex2=xmlDoc.getElementsByTagName("block")[blockLenth2.length-1];
      fieldindex2.appendChild(field2);

      var color=xmlDoc.createAttribute("name");
      color.nodeValue="color";
      x=xmlDoc.getElementsByTagName("field");    
      x[x.length-1].setAttributeNode(color);


    }
    */

    xml = new XMLSerializer().serializeToString(xmlDoc);

    workspace.clear();
    try {
        var xmlDoc = Blockly.Xml.textToDom(xml);
    } catch (e) {
        alert('Error parsing XML:\n' + e);
        return;
    }
    Blockly.Xml.domToWorkspace(xmlDoc, workspace);

}
//workspace.registerButtonCallback(myFirstButtonPressed, changecolor);
function blocklyDivResizew(ratiow) {
    var blocklyDiv = document.getElementById("blocklyDiv");
    blocklyDiv.style.width = parseFloat(blocklyDiv.style.width) * ratiow + "px";
    Blockly.svgResize(workspace);
}

function blocklyDivResizeh(ratioh) {
    var blocklyDiv = document.getElementById("blocklyDiv");
    blocklyDiv.style.height = parseFloat(blocklyDiv.style.height) * ratioh + "px";
    Blockly.svgResize(workspace);
}

function blocklyDivChangeWidth(width) {
    var blocklyDiv = document.getElementById("blocklyDiv");
    blocklyDiv.style.width = parseInt(width) + "px";
    Blockly.svgResize(workspace);
}

function blocklyDivChangeHeight(height) {
    var blocklyDiv = document.getElementById("blocklyDiv");
    blocklyDiv.style.height = parseInt(height) + "px";
    Blockly.svgResize(workspace);
}

function resizeToolbox(isDefaultSize) {
    if (isDefaultSize) {
        mToolboxWidth = 211;
        tool = tool.replace(label2, label1);
        tool2 = tool2.replace(label2, label1);
    } else {
        tool = tool.replace(label1, label2);
        tool2 = tool2.replace(label1, label2);
        mToolboxWidth = 280;
    }
    var ftype=GetFlightDeviceType();
    
    if(flightDeviceType=='F400')
    {
        workspace.updateToolbox(tool);
    }
    else
    {
      workspace.updateToolbox(tool2);
    }
    workspace.scrollCenter();
}

function resizeToolboxW(width) {
    mToolboxWidth = width;
    
    var ftype=GetFlightDeviceType();
    
    if(flightDeviceType=='F400')
    {
        workspace.updateToolbox(tool);
    }
    else
    {
      workspace.updateToolbox(tool2);
    }
    workspace.scrollCenter();
}
var flightDeviceType='F400';
function SetFlightDeviceType(ftype)
{
    flightDeviceType=ftype;
    if(flightDeviceType=='F400')
    {
		console.log(1);
        workspace.updateToolbox(tool);
    }
    else
    {
		console.log(2);
      workspace.updateToolbox(tool2);
    }
}
function GetFlightDeviceType()
{
    var ftype=flightDeviceType;
    return ftype;
}